package com.ecarx.module_network.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ecarx.library_base.BaseApplication;
import com.ecarx.library_base.base_fragment.BaseFragment;
import com.ecarx.library_base.base_widget.InputDialog;
import com.ecarx.library_base.base_widget.ItemCommenView;
import com.ecarx.module_network.R;
import com.ecarx.module_network.utils.WifiCallBack;
import com.ecarx.module_network.controller.WifiController;
import com.ecarx.module_network.adapter.WifiListAdapter;
import com.ecarx.module_network.bean.WifiInfo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Wifi页面
 */
public class LeftWlanFragment extends BaseFragment implements WifiCallBack {
    private ItemCommenView mWlanSwitch, mConnectWlan;
    private LinearLayout mLlWlan;
    private RecyclerView mRecyWifiList;
    private ProgressBar mIvLoading;
    private TextView mTvConnect;
    private boolean mIsOpen;
    private WifiController mWifiProxy;
    private List<WifiInfo> mRealWifiList = new ArrayList<>();
    private WifiListAdapter mAdapter;
    private String mConnectSSID = "";


    @Override
    protected int layoutId() {
        return R.layout.fragment_wlan_left;
    }

    @Override
    protected void init(View view) {
        mWlanSwitch = view.findViewById(R.id.wlan_switch);
        mConnectWlan = view.findViewById(R.id.connect_wlan);
        mTvConnect = view.findViewById(R.id.tv_connect_name);
        mLlWlan = view.findViewById(R.id.ll_wifi);
        mRecyWifiList = view.findViewById(R.id.recycler);
        mIvLoading = view.findViewById(R.id.iv_loading);
        mAdapter = new WifiListAdapter(getActivity(), mRealWifiList);
        mRecyWifiList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyWifiList.setAdapter(mAdapter);
        initData();

    }

    private void initData() {
        mWifiProxy = WifiController.getInstance();
        mIsOpen = mWifiProxy.isWifiEnable();
        setCurWifi("");
        setSwitchState(mIsOpen);
        mWifiProxy.addWifiCallBack(this);
        mWifiProxy.init();
        mWlanSwitch.setOnClickListener(v -> {
            mIsOpen = !mIsOpen;
            changeOpen();
        });

        mAdapter.setOnItemClickListener((view, postion, o) -> {
            WifiInfo wifiBean = mRealWifiList.get(postion);
            Log.i(TAG, "onItemClick: wifiBean=" + wifiBean.toString());
            mWifiProxy.onClickConnectWifi(wifiBean);
        });
    }


    /**
     * 开关Wifi事件
     */
    private void changeOpen() {
        mWifiProxy.setWifiEnable(mIsOpen);
        setCurWifi("");
    }


    /**
     * 开关显示
     *
     * @param switchState
     */
    public void setSwitchState(boolean switchState) {
        if (!switchState) {
            mWlanSwitch.setInfo(getString(R.string.wlan), R.mipmap.img_switch_close);
            mLlWlan.setVisibility(View.GONE);
            mIvLoading.setVisibility(View.GONE);
            mRealWifiList.clear();
            mAdapter.notifyDataSetChanged();
        } else {
            mWlanSwitch.setInfo(getString(R.string.wlan), R.mipmap.img_switch_open);
            mLlWlan.setVisibility(View.VISIBLE);
            mIvLoading.setVisibility(View.VISIBLE);

        }
    }

    @Override
    public void recWifiState(WifiController.OpenState openState) {
        setSwitchState(openState == WifiController.OpenState.OPEN);
    }

    @Override
    public void recWifiConnectSuccess(String ssid, android.net.wifi.WifiInfo wifiInfo) {
        setCurWifi(ssid);
        if (mWifiProxy.getWifiState() == WifiController.OpenState.COLLECTED) {
            recRefreshWifiInfo();
        }
        Log.i(TAG, "recWifiConnectSuccess: " + ssid);
    }

    @Override
    public void recWifiConnectFailure(String ssid) {
        showToast(getString(R.string.wifi_psd_error));
        Log.i(TAG, "recWifiConnectFailure: " + ssid);
    }

    @Override
    public void recWifiTimeOut() {
        showToast(getString(R.string.wifi_connect_timeout));
        recRefreshWifiInfo();
    }

    @Override
    public void recWifiDisConnectSuccess() {
        Log.i(TAG, "recWifiDisConnectSuccess: ");
        mWifiProxy.resetConnectWifi();
        setCurWifi("");
    }

    @Override
    public void recWifiSignalChanged() {
        Log.i(TAG, "recWifiSignalChanged: ");
        if (mWifiProxy.getConnectWifi() != null) {
            setCurWifi(mWifiProxy.getConnectWifi().getSsid());
        }


    }

    @Override
    public void recRefreshWifiInfo() {
        List<WifiInfo> wifiList = mWifiProxy.getAllList();
        if (wifiList != null) {
            wifiList = wifiList.stream().filter(item -> !item.getSsid().equals(mConnectSSID)).collect(Collectors.toList());
            mRealWifiList.clear();
            mRealWifiList.addAll(wifiList);
            mIvLoading.setVisibility(View.GONE);
            mAdapter.notifyDataSetChanged();
            Log.i(TAG, "recRefreshWifiInfo: ");
        }
    }


    @Override
    public void recEncryptWifi(WifiInfo wifiInfo) {
        InputDialog inputDialog = new InputDialog(getActivity(), "", wifiInfo.getSsid(), (pswd) -> {
            recWifiDisConnectSuccess();
            mWifiProxy.setConnectingWifi(wifiInfo);
            mWifiProxy.connect(mWifiProxy.getConnectingWifi().getSsid(), pswd, mWifiProxy.getConnectingWifi().getSecurity());
            recRefreshWifiInfo();
        }, InputDialog.passwordType);
        if (!inputDialog.isShowing()) {
            inputDialog.show();
        }
    }

    @Override
    public void switchWifiOpen() {
        if (mIsOpen) {
            mIsOpen = false;
            changeOpen();
        }
    }


    private void setCurWifi(String wifiName) {
        this.mConnectSSID = wifiName;
        if (!TextUtils.isEmpty(wifiName)) {
            if (mWifiProxy.getConnectWifi() != null) {
                mConnectWlan.setInfo(wifiName, mWifiProxy.getConnectWifi().getWifiLevelImage());
            } else {
                mConnectWlan.setInfo(wifiName, R.drawable.ic_wifi_signal_4);
            }
            mConnectWlan.setLeftTextColor(ColorStateList.valueOf(Color.BLUE));
            mConnectWlan.setVisibility(View.VISIBLE);
            mTvConnect.setVisibility(View.VISIBLE);
        } else {
            mConnectWlan.setVisibility(View.GONE);
            mTvConnect.setVisibility(View.GONE);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWifiProxy != null) {
            mWifiProxy.release();
            mWifiProxy = null;
        }
    }
}
